<template>
  <div class="project-home-container">
    <div class="project-home-header">
      <div class="header-left">
        <img :src="systemLogo" alt="logo" />
        <!-- <span class="system-title">欢迎登录 {{ systemName }}</span> -->
        <chooseProject @onSelect="handleSelect($event)"></chooseProject>
      </div>
      <div class="header-right">
        <div class="item-operate" v-if="userAccount == 'projectListPage'">
          <a-tooltip class="header-item" title="进入系统" placement="bottom">
            <span @click="handleSystem()">
              <icon-fonts icon="icon-jinruxitong"></icon-fonts>
            </span>
          </a-tooltip>
        </div>
        <div class="item-operate">
          <a-tooltip class="header-item" title="操作手册" placement="bottom">
            <span @click="handleDownload()">
              <icon-fonts icon="icon-read"></icon-fonts>
            </span>
          </a-tooltip>
        </div>
        <header-avatar class="header-item" />
      </div>
    </div>
    <div class="screen-conditions-container">
      <ScreenConditions :isDataType="false">
        <template slot="conditions">
          <a-input
            style="width:360px"
            placeholder="请输入项目名称"
            v-model="condition.proName"
          ></a-input>
        </template>
        <template slot="operate">
          <a-button class="cu-btn-primary" icon="search" @click="search()">
            查询
          </a-button>
          <a-button class="cu-btn-filter" icon="reload" @click="reset()">
            重置
          </a-button>
          <div class="near-container">
            <div
              class="item "
              :class="[activeIndex == 1 && 'active']"
              @click="handleViewType(1)"
            >
              <a-icon type="eye" />最近查看项目({{
                projectCount.zjCount || 0
              }}个)
            </div>
            <div class="sep-line">|</div>
            <div
              class="item"
              :class="[activeIndex == 0 && 'active']"
              @click="handleViewType(0)"
            >
              <icon-fonts icon="icon-xiangmu2"></icon-fonts>全部项目({{
                projectCount.allCount || 0
              }}个)
            </div>
          </div>
        </template>
      </ScreenConditions>
    </div>
    <div class="project-home-body">
      <div class="project-home-list">
        <div class="loader" v-if="loading">
          <a-spin />
        </div>
        <a-empty v-if="tableData.length == 0" />
        <a-row v-else :gutter="[24, 24]">
          <a-col
            :xs="24"
            :sm="24"
            :md="12"
            :lg="12"
            :xl="8"
            :xxl="6"
            :xxxl="6"
            v-for="(item, index) in tableData"
            :key="index"
          >
            <div class="project-card" @click="handleActive(item)">
              <div class="bg">
                <img
                  v-if="getUrl(item.proImage)"
                  :src="getUrl(item.proImage)"
                  alt=""
                  srcset=""
                />
                <div v-else class="warp"></div>
              </div>
              <div class="content">
                <div class="name">
                  <a-tooltip>
                    <template slot="title">
                      {{ item.proName }}
                    </template>
                    {{ item.proName }}
                  </a-tooltip>
                </div>
                <div class="introduce">
                  <div class="people">
                    <icon-fonts icon="icon-renyuan" />
                    负责人： {{ item.contacts || "-" }}
                  </div>
                  <div class="amount">
                    <icon-fonts icon="icon-touzi" />
                    投资额：{{
                      Number(item.roadMoney || 0).toLocaleString()
                    }}万元
                  </div>
                </div>
              </div>
            </div>
          </a-col>
        </a-row>
      </div>
      <div class="project-home-page">
        <vxe-pager
          size="small"
          background
          :current-page.sync="pager.page"
          :page-size.sync="pager.pageSize"
          :total="pager.total"
          :layouts="['PrevPage', 'JumpNumber', 'NextPage', 'Sizes']"
          :page-sizes="[8, 16, 32, 80]"
          @page-change="paginationChange"
        >
          <template #left>
            <div class="vxe-pager-left-tip-container">
              共<span>{{ pager.total }}</span
              >条
            </div>
          </template>
        </vxe-pager>
      </div>
    </div>
  </div>
</template>

<script>
import { mapGetters } from "vuex";
import { axios } from "@/utils/request";
import ScreenConditions from "@/components/extendCustom/ScreenConditions";
import { getListProject } from "@/services/user.js";
import HeaderAvatar from "@/layouts/header/HeaderAvatar";
import chooseProject from "./components/chooseProject";
import { flatTreeData } from "@/utils/util.js";
export default {
  components: {
    ScreenConditions,
    HeaderAvatar,
    chooseProject,
  },
  data() {
    return {
      activeIndex: 1,
      condition: {
        //项目名称
        proName: "",
        //项目id
        parentOrgId: "",
      },
      loading: true,
      tableData: [],
      pager: {
        page: 1,
        pageSize: 8,
        total: 0,
      },
      currentProject: {},
      projectCount: {},
    };
  },
  computed: {
    ...mapGetters([
      "menuData",
      "configData",
      "nickname",
      "systemName",
      "userAccount",
      "tenantData",
    ]),
    systemLogo() {
      let index = this.configData.findIndex(
        (item) => item.code === "systemLogo"
      );
      if (index >= 0) {
        return this.configData[index].value;
      } else {
        return "";
      }
    },
    systemName() {
      let index = this.configData.findIndex(
        (item) => item.code === "systemName"
      );
      if (index >= 0) {
        return this.configData[index].value;
      } else {
        return "低代码开发平台";
      }
    },
  },
  mounted() {
    this.resetData();
  },
  methods: {
    //记录最近查看项目
    getProjectCount() {
      let { parentOrgId } = this.condition;
      axios
        .post(
          `/mdata/sysProject/getProListByQXCount`,
          {
            parentOrgId,
          },
          {
            headers: {
              "Content-Type": "application/json",
            },
          }
        )
        .then((res) => {
          let { data } = res || {};
          this.projectCount = {
            allCount: data?.allCount || 0,
            zjCount: data?.zjCount || 0,
          };
        })
        .catch((_) => {
          this.projectCount = {};
        })
        .finally((_) => {});
    },

    //筛选项目
    handleSelect(ev) {
      this.currentProject = ev;
      this.condition.parentOrgId = ev.id;
      this.getTableData();
      this.getProjectCount();
    },
    handleViewType(index) {
      this.activeIndex = index;
      this.getTableData();
    },

    resetData() {
      localStorage.setItem("TO_XMDP", JSON.stringify(false));
      localStorage.setItem("CURRENT_PROJECT", JSON.stringify({}));
      localStorage.setItem("CURRENT_PROJECT_CODE", "");
      this.$store.dispatch("setStoreState", {
        CURRENT_PROJECT: {},
      });
      this.$store.dispatch("setStoreState", {
        CURRENT_PROJECT_CODE: "",
      });
    },

    //刷新权限/菜单数据
    async refreshPermission(data = {}, toXmdp) {
      let { proCode, orgCode } = data;
      //缓存所选项目
      localStorage.setItem("CURRENT_PROJECT", JSON.stringify(data));
      localStorage.setItem("CURRENT_PROJECT_CODE", proCode || orgCode);
      this.$store.dispatch("setStoreState", {
        CURRENT_PROJECT: data,
      });
      this.$store.dispatch("setStoreState", {
        CURRENT_PROJECT_CODE: proCode || orgCode,
      });
      //
      await this.$store.dispatch("getPermissionIdentifyingByRoleId");
      await this.$store
        .dispatch("getUserInForAndButtonPermissions")
        .then(async (res) => {
          const roles = res && res.role;
          //菜单信息
          let menuSource = await this.$store.dispatch("GenerateRoutes", {
            roles,
          });

          //首页信息
          let portalSource = JSON.parse(
            localStorage.getItem("PORTAL_ROUTERS_DATA" ?? "[]")
          );

          //默认获取一级节点菜单
          let flatMenu = flatTreeData(menuSource, "children");
          let firstMenu = flatMenu.find(
            (v) => !v.children || v.children.length == 0
          );

          //是否有大屏权限
          if (toXmdp) {
            //进入大屏
            this.$router.push({
              path: `/largeScreen`,
            });
          } else {
            //没有首页，有菜单
            if (portalSource.length == 0 && menuSource.length != 1) {
              this.$router.push({
                path: firstMenu.fullPath,
              });
            }
            //没有首页，没有菜单
            else if (portalSource.length == 0 && menuSource.length == 1) {
              this.$router.push({
                path: `/whitePage/index`,
              });
            }
            //有首页，有菜单
            else {
              this.$router.push({
                path: "/system/portal/index",
              });
            }
          }
        });
    },

    //进入系统
    async handleSystem() {
      //   let flatData = flatTreeData(this.tenantData, "children");
      await this.refreshPermission(this.currentProject, false);
    },

    //操作手册
    handleDownload() {
      window.open(
        "https://dpmp.jkec.info/docs/数字项目管理平台用户操作手册.pdf"
      );
    },

    //选择项目
    async handleActive(item) {
      let { proCode, toXmdp } = item;
      //
      localStorage.setItem("TO_XMDP", JSON.stringify(toXmdp));
      //
      await this.refreshPermission(item, toXmdp);
      //设置最近查看项目
      await this.getRecentlyProject(proCode);
    },

    //记录最近查看项目
    getRecentlyProject(proCode) {
      axios
        .post(
          `/mdata/sysProject/projectVisitSet`,
          {
            proCode,
          },
          {
            headers: {
              "Content-Type": "application/json",
            },
          }
        )
        .then((res) => {})
        .catch((_) => {})
        .finally((_) => {});
    },

    //查询大屏id
    getScreenId(proCode) {
      let user_info = JSON.parse(localStorage.getItem("USER_INFO") ?? "{}");
      axios
        .post(
          `/report/reportVisual/queryEnabledByTenantUuid`,
          {
            tenantUuid: proCode,
            userId: user_info.uuid,
          },
          {
            headers: {
              "Content-Type": "application/json",
            },
          }
        )
        .then((res) => {
          let { data } = res;
          let { uuid } = data;
          if (uuid) {
            //进入大屏
            this.$router.push({
              path: `/largeScreen?uuid=${uuid}&proCode=${proCode}`,
            });
          } else {
            //进入系统
            this.$router.push({
              path: `/system/portal/index`,
            });
          }
        })
        .catch((_) => {
          //进入系统
          this.$router.push({
            path: `/system/portal/index`,
          });
        });
    },

    getUrl(data = "[]") {
      return JSON.parse(data)?.[0]?.url ?? "";
    },

    search() {
      this.pager.page = 1;
      this.getTableData();
    },
    reset() {
      this.condition.proName = "";
      this.search();
    },

    getTableData() {
      this.loading = true;
      return new Promise((resolve, reject) => {
        let { page, pageSize } = this.pager;
        let { proName = "", parentOrgId = "" } = this.condition;
        getListProject({
          page,
          pageSize,
          proName,
          proId: "",
          parentOrgId,
          viewType: this.activeIndex,
        })
          .then((res) => {
            let { data } = res;
            this.tableData = data?.rows ?? [];
            this.pager.total = data?.totalCount ?? 0;
            resolve();
          })
          .catch((_) => {
            this.tableData = [];
            this.pager.total = 0;
            reject();
          })
          .finally((_) => {
            this.loading = false;
          });
      });
    },

    //监听分页切换
    paginationChange({ currentPage, pageSize }) {
      this.pager.page = currentPage;
      this.pager.pageSize = pageSize;
      this.getTableData();
    },
  },
};
</script>

<style lang="less" scoped>
.project-home-container {
  height: 100%;
  display: flex;
  flex-direction: column;
  padding: 0 0 60px 0;
  box-sizing: border-box;
  overflow: hidden;
  .project-home-header {
    height: 54px;
    background: #fff;
    margin-bottom: 16px;
    display: flex;
    justify-content: space-between;
    padding: 0 40px 0 20px;
    .header-left {
      display: flex;
      align-items: center;
      img {
        width: 80px;
        height: 50px;
        object-fit: contain;
      }
      .system-title {
        font-weight: bold;
        font-size: 16px;
        color: #333;
      }
    }
    .header-right {
      display: flex;
      align-items: center;
      .item-operate {
        margin-right: 20px;
        &:last-of-type {
          margin-right: 0;
        }
      }
    }
  }

  .screen-conditions-container {
    padding: 0 100px;
    box-sizing: border-box;
    margin-bottom: 16px;
    .conditions-screening-container {
      background: unset;
      .near-container {
        position: absolute;
        right: 10px;
        top: 50%;
        transform: translateY(-50%);
        display: flex;
        align-items: center;
        font-weight: 400;
        font-size: 14px;
        color: #8a9295;
        .sep-line {
          margin: 0 10px;
        }
        .item {
          cursor: pointer;
          &.active {
            color: #1890ff;
          }
        }
        /deep/.anticon {
          font-size: 16px;
          margin-right: 8px;
          position: relative;
          top: 1px;
        }
      }
    }
  }
  .project-home-body {
    flex: 1;
    display: flex;
    flex-direction: column;
    overflow: hidden;
    .project-home-list {
      flex: 1;
      padding: 0 100px;
      box-sizing: border-box;
      overflow: auto;
      overflow-x: hidden;
      position: relative;
      .project-card {
        width: 100%;
        height: 324px;
        background: #ffffff;
        border-radius: 4px 4px 4px 4px;
        display: flex;
        flex-direction: column;
        box-shadow: 0px 4px 16px 0px rgba(102, 102, 102, 0.1);
        .bg {
          height: 200px;
          width: 100%;
          img {
            border-radius: 4px 4px 0 0;
            height: 100%;
            width: 100%;
            object-fit: cover;
          }
          .warp {
            border-radius: 4px 4px 0 0;
            height: 100%;
            width: 100%;
            background: url(~@/assets/img/home/project.png);
            background-size: 100% 100%;
          }
        }
        .content {
          flex: 1;
          padding: 20px 16px;
          box-sizing: border-box;
          display: flex;
          flex-direction: column;
          justify-content: space-between;
          .name {
            font-weight: 400;
            font-size: 18px;
            color: #333333;
            // 设置两行文字溢出
            -webkit-line-clamp: 2;
            /** 对象作为伸缩盒子模型显示 **/
            display: -webkit-box;
            /** 设置或检索伸缩盒对象的子元素的排列方式 **/
            -webkit-box-orient: vertical;
            /** 隐藏超出的内容 **/
            overflow: hidden;
          }
          .introduce {
            font-weight: 400;
            font-size: 14px;
            color: #8a8a8c;
            display: flex;
            justify-content: space-between;
            .people,
            .amount {
              display: flex;
              align-items: center;
              justify-content: space-between;
            }
            .people {
              /deep/.anticon {
                color: #80e0db;
                position: relative;
                top: -1px;
              }
            }
            .amount {
              /deep/.anticon {
                color: #f07f17;
                position: relative;
                top: -1px;
              }
            }
          }
          /deep/.anticon {
            margin-right: 8px;
          }
        }
        &:hover {
          box-shadow: 0px 6px 16px 0px rgba(24, 144, 255, 0.2);
          border-radius: 6px 6px 6px 6px;
          border: 1px solid rgba(24, 144, 255, 0.4);
          cursor: pointer;
          .content {
            .name {
              color: #1890ff;
            }
            .introduce {
              color: #1890ff;
              /deep/.anticon {
                color: #1890ff;
              }
            }
          }
        }
      }
      .loader {
        height: 100%;
        width: 100%;
        position: absolute;
        left: 50%;
        top: 50%;
        transform: translate(-50%, -50%);
        z-index: 22;
        display: flex;
        align-items: center;
        justify-content: center;
      }

      /deep/.ant-empty {
        position: absolute;
        left: 50%;
        top: 50%;
        transform: translate(-50%, -50%);
      }
    }
    .project-home-page {
      padding: 0 100px;
      box-sizing: border-box;
      flex-shrink: 0;
      /deep/.vxe-pager {
        background: unset;
      }
    }
  }
}
</style>
